<template>
  <div id="map" style="height: 500px; width: 540px"></div>
</template>

<script>
import "ol/ol.css";
import Map from "ol/Map";
import View from "ol/View";
import TileLayer from "ol/layer/Tile";
import XYZ from "ol/source/XYZ";
import ZoomTo from "ol/control/ZoomToExtent";
import ZoomSlider from "ol/control/ZoomSlider";
import FullScreen from "ol/control/FullScreen";
// import { transform } from "ol/proj";
import Feature from "ol/Feature";
import Point from "ol/geom/Point";
import { Circle, Icon, Fill, Stroke, Style, Text } from "ol/style"; //
import Vector from "ol/source/Vector";
import Vect from "ol/layer/Vector";
import GeoJSON from "ol/format/GeoJSON";
import Cluster from "ol/source/Cluster";
export default {
  name: "mapItem",
  props: {
    mapData: Array,
  },
  data() {
    return {
      isActive: true,
      mapArr: [],
      layer: "",
    };
  },
  methods: {
    btnMap() {
      const map = new Map({
        target: "map",
        layers: [
          new TileLayer({
            source: new XYZ({
              // url: "http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}",
              // wrapX: false
              url: "http://192.168.1.66:8081" + "/{z}/{x}/{y}.png",
            }),
          }),
        ],
        view: new View({
          center: [116.405285, 39.904989], //中心点 经度、纬度
          zoom: 6, // 设置缩放级别
          minZoom: 1, // 设置最小缩放级别
          maxZoom: 12, // 设置最大缩放级别
          // center: transform([109, 34], 'EPSG:4326', 'EPSG:3857')
          projection: "EPSG:4326", //'EPSG:3857'这是投影坐标类型
          extent: [73.66, 3.86, 135.05, 53.55], //中国边界
        }),
      });

      /* 视图跳转控件 [106.6670034817791, 31.8190515]*/
      const ZoomToExtent = new ZoomTo({
        extent: [110, 30, 160, 30], //显示的坐标
      });
      map.addControl(ZoomToExtent);
      // /* 放大缩小控件 */
      const zoomslider = new ZoomSlider();
      map.addControl(zoomslider);
      // //全屏控件
      const fullScreen = new FullScreen();
      map.addControl(fullScreen);
      // /* 1、构建要素 pointermove*/
      // this.addPoint(map, [114.3, 30.5], "1");
      map.on("pointermove", (e) => {
        console.log(e.coordinate, 111);
      });

      map.on("click", (e) => {
        console.log(e);
        let { coordinate } = e;
        console.log(coordinate);
        let features = this.layer.getSource().getFeatures();
        console.log(features, 988);
        var pixel = map.getEventPixel(e.originalEvent);
        var currentFeature = map.forEachFeatureAtPixel(
          pixel,
          function (feature) {
            return feature;
          }
        );
        console.log(currentFeature, 1234);
        let selectedStyle = new Style({
          image: new Circle({
            radius: 30,
            stroke: new Stroke({
              width: 4,
              color: "red",
            }),
            fill: new Fill({
              color: "green",
            }),
          }),
          stroke: new Stroke({
            width: 4,
            color: "red",
          }),
          fill: new Fill({
            color: "green",
          }),
        });
        currentFeature.setStyle(selectedStyle);
        console.log(selectedStyle);
      });
      console.log(this.mapArr, 111);
      // this.addLine(map, this.mapArr);
      // this.addPoint(map, this.mapArr);
      this.mapArr.forEach((item, index) => {
        this.addPoint(map, item, (index + 1).toString());
      });
      //LineString线要素 Polygon:区要素
      //LineString线要素 Polygon:区要素
      this.addArrow(map);
    },
    // 添加点要素
    addPoint(map, arr, name) {
      const point = new Feature({
        geometry: new Point(arr),
        name: name,
      });
      point.setId(name); // 设置ID
      const style = new Style({
        text: new Text({
          text: name,
          // offsetY: -35,
          fill: new Fill({ color: "#000" }),
          stroke: new Stroke({ color: "#fff", width: 2 }),
        }),
        image: new Circle({
          radius: Math.random() * (7.2 - 5.5) + 5.5,
          fill: new Fill({
            color: this.getRandomColor(),
          }),
          stroke: new Stroke({
            color: this.getRandomColor(),
            width: 1,
          }),
        }),
      });
      point.setStyle(style);
      const source = new Vector({
        features: [point],
      });
      let cluster = new Cluster({
        distance: 25, //设置聚合标注的距离,
        source: source,
      });
      this.layer = new Vect({
        source: cluster,
        style: () => {
          return new Style({
            text: new Text({
              text: name,
              // offsetY: -35,
              fill: new Fill({ color: "#000" }),
              stroke: new Stroke({ color: "#fff", width: 2 }),
            }),
            image: new Circle({
              radius: Math.random() * (7.2 - 5.5) + 5.5,
              fill: new Fill({
                color: this.getRandomColor(),
              }),
              stroke: new Stroke({
                color: this.getRandomColor(),
                width: 1,
              }),
            }),
          });
        },
      });
      map.addLayer(this.layer);
    },

    // addPoint(map, arr) {
    //   let point = [];
    //   console.log(arr, 222);
    //   for (let i = 0; i < arr.length; i++) {
    //     point.push(
    //       new Feature({
    //         geometry: new Point(arr[i]), //几何信息 坐标
    //         name: i + 1,
    //       })
    //     );
    //   }
    //   console.log(point, 666);

    //   let style = new Style({
    //     text: new Text({
    //       // text: 1, // 假设点要素有一个'num'属性，或者从其他地方获取编号
    //       fill: new Fill({ color: "#000" }),
    //       stroke: new Stroke({ color: "#fff", width: 3 }),
    //     }),
    //     // image属性设置点要素的样式
    //     image: new Circle({
    //       radius: 8, //点的半径 单位： 度
    //       fill: new Fill({
    //         color: "#ff2d51",
    //       }),
    //       // stroke设置描边 类似于边框
    //       stroke: new Stroke({
    //         color: "#333",
    //         width: 1,
    //       }),
    //     }),
    //   });
    //   // 未选中样式

    //   point.forEach((item, i) => {
    //     style.text_.text_ = i + 1;
    //     console.log(style, i + 1);
    //     style.text = new Text({
    //       text: i + 1, // 假设点要素有一个'num'属性，或者从其他地方获取编号
    //       fill: new Fill({ color: "#000" }),
    //       stroke: new Stroke({ color: "#fff", width: 3 }),
    //     });
    //     console.log(style.text, 333);
    //     item.setStyle(style);
    //   });
    //   /* 2、将要素添加到矢量数据源 */
    //   const source = new Vector({
    //     features: point,
    //   });
    //   /* 3、将矢量数据源添加到矢量图层 */
    //   this.layer = new Vect({
    //     source,
    //   });
    //   /* 4、将矢量图层添加到地图容器 */
    //   map.addLayer(this.layer);
    // },
    // 添加线要素
    addLine(map, mapArr) {
      let data = {
        type: "FeatureCollection",
        features: [
          {
            type: "Feature",
            geometry: {
              type: "LineString",
              coordinates: mapArr,
            },
          },
        ],
      };
      //设置矢量数据源读取数据
      let source = new Vector({
        features: new GeoJSON().readFeatures(data),
      });
      // 设置线样式
      let style = new Style({
        stroke: new Stroke({
          color: "#ff2d51",
          width: 2,
        }),
      });
      // 设置矢量图层
      let layer = new Vect({
        source,
      });
      layer.setStyle(style);
      // 添加到地图容器
      map.addLayer(layer);
    },
    // createClusterLabel(map, arr) {
    //   // 初始化标签要素
    //   console.log(map);
    //   let feature = new Feature({
    //     geometry: new Point(arr[0]), // 标签位置
    //     name: data.name, // 标注显示的文字
    //     img: require("./../../assets/imgs/map_icon_location.png"), // 标注显示的logo图片
    //   });
    //   feature.setId(1); // 设置ID
    //   let source = new Vector({}); // 初始化矢量数据源
    //   source.addFeature(feature); // 将标签要素添加至矢量数据源
    //   let cluster = new Cluster({
    //     // 创建聚合标注对象
    //     distance: 25, // 设置聚合标注的距离
    //     source: source,
    //   });
    //   let layer = new Vectors({
    //     // 创建矢量图层
    //     source: cluster,
    //     style: function (feature, resolutions) {
    //       // 这里可以参照上面的createLableStyle写，聚合标注在feature中单独设置的样式不生效
    //       return new OlStyleStyle({
    //         image: new OlStyleIcon({
    //           // src: feature.values_.features[0].values_.img, // 图片路径
    //         }),
    //       });
    //     },
    //   });
    //   this.map.addLayer(layer); // 将聚合标注添加至地图
    // },
    // 箭头
    addArrow(map) {
      let arrowStyle = new Style({
        image: new Icon({
          src: "@/assets/arrow.png",
          anchor: [0.5, 0.5],
          scale: 0.5,
          rotateWidthView: true,
        }),
      });
      let arrowFeature = new Feature({
        geometry: new Point([105.3, 32.5]),
        style: arrowStyle,
      });
      map.addFeature(arrowFeature);
    },
    getMinMaxPonit() {
      let minlongitude = 0;
      let maxlongitude = 0;
      let minlatitude = 0;
      let maxlatitude = 0;
      this.mapArr.forEach((item, index) => {
        if (index === 0) {
          minlongitude = item[0];
          maxlongitude = item[0];
          minlatitude = item[1];
          maxlatitude = item[1];
        } else {
          if (item[0] < minlongitude) {
            minlongitude = item[0];
          }
          if (item[0] > maxlongitude) {
            maxlongitude = item[0];
          }
          if (item[1] < minlatitude) {
            minlatitude = item[1];
          }
          if (item[1] > maxlatitude) {
            maxlatitude = item[1];
          }
        }
      });
      this.extentPoint.push(minlongitude - 1);
      this.extentPoint.push(minlatitude - 1);
      this.extentPoint.push(maxlongitude + 1);
      this.extentPoint.push(maxlatitude + 1);
    },
    hasSmallLong(arr) {
      let arrI = [];
      let arrJ = [];
      for (let j = 0; j < arr.length; j++) {
        let index0 = arr[j].longitude;
        for (let i = j + 1; i < arr.length; i++) {
          if (Math.abs(index0 - arr[i].longitude) < 0.001) {
            arrJ.push(j);
            arrI.push(i);
          }
        }
      }

      return [...new Set([...arrI, ...arrJ])];
    },
    hasSmallPoint(arrData, arr) {
      let arrPoint = [];
      for (let j = 0; j < arr.length; j++) {
        let index0 = arrData[arr[j]].latitude;
        for (let i = j + 1; i < arr.length; i++) {
          if (Math.abs(index0 - arrData[arr[i]].latitude) < 0.001) {
            arrPoint.push(arr[j]);
            arrPoint.push(arr[i]);
          }
        }
      }
      return [...new Set([...arrPoint])]; //返回最终需要改变的数组坐标
    },
    changePoint(arr) {
      for (let i = 0; i < arr.length; i++) {
        this.mapArr[arr[i]][0] =
          this.mapArr[arr[i]][0] + (Math.random() - 0.5) * 0.003;
        this.mapArr[arr[i]][1] =
          this.mapArr[arr[i]][1] + (Math.random() - 0.5) * 0.003;
      }
    },
    getRandomColor() {
      const letters = "0123456789ABCDEF";
      let color = "#";
      for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
      }
      return color;
    },
  },
  mounted() {
    let arr;
    this.mapData.forEach((item) => {
      arr = [];
      arr.push(parseFloat(item.LONGITUDE));
      arr.push(parseFloat(item.LATITUDE));
      this.mapArr.push(arr);
    });
    // this.mapArr.push([115.3, 32.5]);
    console.log(this.mapArr, "mapArr");
    this.btnMap();
  },
};
</script>

<style>
.ol-zoomslider {
  top: 7.5em;
}
</style>
